<template>
  <div class="app-container">
    <el-card shadow="hover">
      <el-input v-model="listQuery.name"
                placeholder="姓名"
                size="small"
                style="width: 100px;" />
      <el-select v-model="listQuery.izEnabled"
                 placeholder="在职情况"
                 size="small"
                 clearable
                 style="width: 110px">
        <el-option v-for="item in getOptions('user_is_enabled')"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.auditState"
                 placeholder="审核状态"
                 clearable
                 size="small"
                 style="width: 110px">
        <el-option v-for="item in getOptions('audit_state')"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.userState"
                 placeholder="使用状态"
                 clearable
                 size="small"
                 multiple
                 collapse-tags
                 style="width: 180px">
        <el-option v-for="item in getOptions('user_state')"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.roleIds"
                 placeholder="角色权限"
                 clearable
                 size="small"
                 multiple
                 collapse-tags
                 style="width: 180px">
        <el-option v-for="item in roleOptions"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
      <el-button v-if="hasPermission('/sysadmin/user/list')"
                 @click="handleGetUserList(1)"
                 plain
                 size="small"
                 type="primary"
                 icon="el-icon-search">
        查询
      </el-button>

      <el-button @click="dialogNewUserVisible = true; beforeCommit = true;"
                 plain
                 size="small"
                 v-if="hasPermission('/sysadmin/user/create')"
                 type="primary"
                 icon="el-icon-plus">
        新增
      </el-button>
      <el-dialog :visible.sync="dialogNewUserVisible"
                 title="新增用户"
                 width="60%">
        <el-form :model="newUserForm"
                 :rules="newUserRules"
                 :disabled="beforeCommit === false"
                 ref="createUserForm"
                 label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名"
                            prop="name">
                <el-input v-model="newUserForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码"
                            prop="mobile">
                <el-input v-model="newUserForm.mobile"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色权限"
                            prop="roleIds">
                <el-select style="width:100%"
                           v-model="newUserForm.roleIds"
                           clearable
                           multiple>
                  <el-option v-for="item in roleOptions"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门"
                            prop="newDepartmentName">
                <el-input :readonly="true"
                          v-model="newUserForm.newDepartmentName">
                  <el-button slot="append"
                             icon="el-icon-more"
                             @click="showDepartmentDrawer('create')"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="备注说明"
                          prop="remark">
              <el-input type="textarea"
                        :rows="2"
                        v-model="newUserForm.remark"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="登录名"
                            prop="username">
                <el-input :disabled="true"
                          v-model="newUserForm.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12"
                    v-show="beforeCommit === false">
              登录密码同登录名, 登录名和密码都可以在用户注册时修改，请通知用户及时注册!
            </el-col>
          </el-row>
          <hr />
          <el-form-item>
            <el-button @click="handleResetForm('createUserForm')">重置
            </el-button>
            <el-button @click="handleSumitCreateUser()"
                       :loading="isLoading">提交保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-button-group>
        <el-button @click="handleDownload()"
                   plain
                   size="small"
                   :loading="isLoading"
                   type="primary"
                   icon="el-icon-download">
          下载
        </el-button>
        <el-button type="primary"
                   plain
                   size="small"
                   :icon="downloadIcon"
                   @click="setDownloadIcon"></el-button>
      </el-button-group>
    </el-card>
    <el-card shadow="never">
      <el-table v-loading="isLoading"
                :data="dataList"
                border
                fit
                highlight-current-row
                style="width: 100%;"
                ref="userTable"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         width="55"> </el-table-column>
        <el-table-column label="行号"
                         type="index"
                         sortable
                         align="center"
                         width="60">
          <template slot-scope="scope">
            <span>{{
                            (paginationOption.currentPage - 1) *
                                paginationOption.pageSize +
                                scope.$index +
                                1
                        }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名"
                         prop="name"
                         width="100px"
                         align="center">
        </el-table-column>
        <el-table-column label="所属部门"
                         align="center">
          <template slot-scope="{ row }">
            <el-tag v-if="isNotEmpty(row.departmentName)"
                    type="success">
              {{ row.departmentName }}
            </el-tag>
            <el-tag type="info"
                    v-if="isNotEmpty(row.newDepartmentName)">
              {{ row.newDepartmentName }}
            </el-tag>
          </template>

        </el-table-column>
        <el-table-column label="电话号码"
                         width="180px"
                         prop="mobile"
                         align="center">
        </el-table-column>
        <el-table-column label="在职情况"
                         width="120px"
                         align="center">
          <template slot-scope="{ row }">
            <el-tag v-if="isNotEmpty(row.izEnabled)"
                    type="success">
              {{getDictLabel("user_is_enabled", row.izEnabled)}}
            </el-tag>
            <el-tag type="info"
                    v-if="isNotEmpty(row.newIsEnabled)">
              {{getDictLabel("user_is_enabled", row.newIsEnabled)}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用状态"
                         width="80px"
                         align="center">
          <template slot-scope="{ row }">
            <span>
              {{getDictLabel("user_state", row.userState)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态"
                         width="80px"
                         align="center">
          <template slot-scope="{ row }">
            <span>
              {{ getDictLabel("audit_state", row.auditState) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色权限"
                         width="120px"
                         align="center">
          <template slot-scope="{ row }">
            <el-tag v-for="n in getRolesAvailable(row)"
                    :key="n"
                    type="success">
              {{ n }}
            </el-tag>
            <el-tag v-for="n in getRolesUnavailable(row)"
                    :key="n"
                    type="info">
              {{ n }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="50px"
                         type="expand">
          <template slot-scope="props">
            <el-form label-position="right"
                     inline
                     class="demo-table-expand">
              <el-form-item label="姓名">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="角色权限">
                <el-divider direction="vertical"></el-divider>
                <el-tag v-for="n in getRolesAvailable(props.row)"
                        :key="n"
                        type="success">
                  {{ n }}
                </el-tag>
                <el-divider direction="vertical"></el-divider>
                <el-tag v-for="n in getRolesUnavailable(props.row)"
                        :key="n"
                        type="info">
                  {{ n }}
                </el-tag>
              </el-form-item>
              <el-form-item label="登录名">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.username }}</span>
              </el-form-item>

              <el-form-item label="所属部门">
                <el-divider direction="vertical"></el-divider>
                <el-tag v-if="isNotEmpty(props.row.departmentName)"
                        type="success">
                  {{ props.row.departmentName }}
                </el-tag>
                <el-divider direction="vertical"></el-divider>
                <el-tag type="info"
                        v-if="isNotEmpty(props.row.newDepartmentName)">
                  {{ props.row.newDepartmentName }}
                </el-tag>
              </el-form-item>
              <el-form-item label="电子邮箱">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.email }}</span>
              </el-form-item>
              <el-form-item label="在职情况">
                <el-divider direction="vertical"></el-divider>
                <el-tag v-if="isNotEmpty(props.row.izEnabled)"
                        type="success">
                  {{getDictLabel("user_is_enabled", props.row.izEnabled)}}
                </el-tag>
                <el-divider direction="vertical"></el-divider>
                <el-tag type="info"
                        v-if="isNotEmpty(props.row.newIsEnabled)">
                  {{getDictLabel("user_is_enabled", props.row.newIsEnabled)}}
                </el-tag>
              </el-form-item>

              <el-form-item label="使用状态">
                <el-divider direction="vertical"></el-divider>
                <span>{{ getDictLabel("user_state", props.row.userState) }}</span>
              </el-form-item>
              <el-form-item label="审核状态">
                <el-divider direction="vertical"></el-divider>
                <span>{{ getDictLabel("audit_state", props.row.auditState) }}</span>
              </el-form-item>
              <el-form-item label="电话号码">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.mobile }}</span>
              </el-form-item>
              <el-form-item label="电话号码">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.mobile }}</span>
              </el-form-item>
              <el-form-item label="创建人员">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.createUserName }}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-divider direction="vertical"></el-divider>
                <span>{{ formatTime(props.row.createTime) }}</span>
              </el-form-item>
              <el-form-item label="审核人员">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.auditUserName }}</span>
              </el-form-item>
              <el-form-item label="审核时间">
                <el-divider direction="vertical"></el-divider>
                <span>{{ formatTime(props.row.auditTime) }}</span>
              </el-form-item>
              <el-form-item label="备注"
                            style="width:100%">
                <el-divider direction="vertical"></el-divider>
                <span>{{ props.row.remark }}</span>
              </el-form-item>
              <el-divider></el-divider>
              <el-button size="mini"
                         type="warning"
                         v-if="hasPermission('/sysadmin/user/disable') && enableBtnUserDiabled(props.row)"
                         :loading="isLoading"
                         @click="handleUserDisabled(props.row)">设置离职
              </el-button>
              <el-button size="mini"
                         type="warning"
                         v-if="hasPermission('/sysadmin/user/enable') && ! enableBtnUserDiabled(props.row)"
                         :loading="isLoading"
                         @click="handleUserEnabled(props.row)">设置在职
              </el-button>
              <el-button v-if="hasPermission('/sysadmin/user/passwordReset')"
                         size="mini"
                         type="warning"
                         @click="handlePasswordReset(props.row)">密码重置
              </el-button>
              <el-button v-if="hasPermission('/sysadmin/user/newDepartment')"
                         size="mini"
                         type="warning"
                         :loading="isLoading"
                         @click="handleNewDepartment(props.row)">部门调整
              </el-button>
              <el-button v-if="hasPermission('/sysadmin/user/newRole')"
                         size="mini"
                         type="warning"
                         :loading="isLoading"
                         @click="handleNewRolesDialog(props.row)">角色调整
              </el-button>
              <el-button v-if="hasPermission('/sysadmin/user/audit')"
                         size="mini"
                         type="warning"
                         :loading="isLoading"
                         @click="handleUserAudit(props.row)">审核批准
              </el-button>
            </el-form>
            <el-dialog :visible.sync="dialogUserRoles"
                       title="角色调整"
                       width="40%">
              <el-form label-position="right"
                       :model="userNewRoles">
                <el-form-item label="当前角色"
                              style="width:100%">
                  <el-divider direction="vertical"></el-divider>
                  <el-tag v-for="n in getRolesAvailable(props.row)"
                          :key="n"
                          type="success">
                    {{ n }}
                  </el-tag>
                </el-form-item>
                <el-form-item label="新角色"
                              style="width:100%">
                  <el-select style="width:100%"
                             v-model="userNewRoles.newRoleIds"
                             readonly
                             multiple>
                    <el-option v-for="item in roleOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-divider></el-divider>
                <el-button size="small"
                           type="warning"
                           @click="dialogUserRoles = false">取消
                </el-button>
                <el-button size="small"
                           type="primary"
                           @click="handleUserNewRoles(props.row)">确定
                </el-button>
              </el-form>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="paginationOption.currentPage"
                       :page-sizes="[50, 100, 200, 300]"
                       :page-size="paginationOption.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="paginationOption.total">
        </el-pagination>
        <!-- <el-button @click="drawer = true">抽屉</el-button> -->
      </div>
    </el-card>

    <el-drawer :visible.sync="departmentDrawer.show"
               :with-header="false"
               :direction="direction">
      <el-card shadow="never">
        <div slot="header"
             class="clearfix">
          <el-form>
            <span>{{departmentDrawer.name}}</span>
            <el-button style="float: right; padding: 3px 0"
                       type="text"
                       :disabled="departmentDrawer.id === -1"
                       @click="handleDepartmentOk">确定</el-button>
            <el-button style="float: right; padding: 3px 20px"
                       type="text"
                       @click="handleDepartmentCancel">取消</el-button>
          </el-form>
        </div>
        <el-tree :data="departments"
                 :highlight-current="true"
                 :expand-on-click-node="false"
                 ref="departmentTree"
                 node-key="id"
                 :default-expand-all="true"
                 @current-change="departmentTreeCurrentChange"
                 :props="defaultProps"></el-tree>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import { formatDate } from "@/utils/date";
import { mapGetters } from "vuex";
import {  apiUserList, apiUserCreate, apiUserListDepartment, apiUserDisable, apiUserEnable, apiUserNewDepartment,
  apiUserAudit, apiUserNewRole, apiUserPasswordReset, apiUserListRole} from "@/api/sysadmin";
import { getLabel, getEntries, hasPermission } from "@/utils/dict";


export default {
  name: "MandyUser",
  data() {
    return {
      departmentDrawer: {
        show: false,
        action: '',  //'create', 'select'
        name: '',
        id: -1
      },

      direction: 'rtl',

      departments: undefined,
      defaultProps: {
        children: 'children',
        label: 'name',
        //checked: 'izAllowed', no work!
      },

      newUserRules: {
        name: [
          {
            required: true,
            message: "请输入新用户姓名",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur"
          }
        ],
        mobile: [
          {
            required: true,
            message: "请输入新用户手机号码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          }
        ],
        roleIds: [
          {
            required: true,
            message: "请为新用户设置角色权限",
            trigger: "change"
          },
          {
            required: true,
            message: "请为新用户设置角色权限",
            trigger: "blur"
          }
        ],
        newDepartmentName: [
          {
            required: true,
            message: "请为新用户设置归属部门",
            trigger: "change"
          },
          {
            required: true,
            message: "请为新用户设置归属部门",
            trigger: "blur"
          },
        ]
      },

      paginationOption: {
        pageSize: 50,
        currentPage: 1,
        total: 0
      },
      dataList: [],
      optionItem: {
        value: "",
        label: ""
      },
      newUserForm: {
        id: undefined,
        name: undefined,
        mobile: undefined,
        roleIds: undefined,
        newDepartmentId: undefined,
        newDepartmentName: undefined,
        remark: undefined,
        username: undefined,
        password: undefined,
      },

      dialogUserRoles: false,
      userNewRoles: {
        roleIds: [],
        newRoleIds: []
      },

      currentUser: undefined,
      isDownloadAllData: false,
      downloadIcon: "el-icon-circle-check",
      multipleSelection: [],
      tHeader: [
        "姓名",
        "登录名",
        "在职情况",
        "使用状态",
        "审核状态",
        "角色权限",
        "备注"
      ],
      filterVal: [
        "name",
        "username",
        "izEnabled",
        "userState",
        "auditState",
        "roles",
        "remark"
      ],

      roleOptions: [],
      //data: JSON.parse(JSON.stringify(data)),
      isLoading: false,
      listQuery: {
        name: undefined,
        //userState is a list
        userState: undefined,
        izEnabled: undefined,
        auditState: undefined,
        //roleIds is a list
        roleIds: [],
        pageSize: 50,
        pageStart: 0
      },

      dialogNewUserVisible: false,
      beforeCommit: false
    };
  },

  created() {
    this.callRoleList();
  },

  computed: {
  },

  methods: {
    ...mapGetters(["dictMap"]),

    hasPermission(url) {
      return hasPermission(url)
    },

    formatTime(time) {
      if (time == null || time === '') {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },

    handleNewRolesDialog(rowData) {
      this.userNewRoles.roleIds = [];
      this.userNewRoles.newRoleIds = [];
      rowData.myRoles.forEach(element => {
        if (element.relationState === "1") {
          this.userNewRoles.roleIds.push(element.id);
        } else {
          this.userNewRoles.newRoleIds.push(element.id);
        }
      });
      this.dialogUserRoles = true;
    },

    messageSuccess() {
      this.$message({
        type: 'success',
        message: '提交成功!',
        duration: 3000
      });
    },

    handleUserNewRoles(rowData) {
      this.isLoading = true;
      let user = Object.assign({}, rowData);
      user.myRoles = [];

      for (let i = 0; i < this.userNewRoles.newRoleIds.length; i++) {
        let role = {};
        role.relationState = "0";
        role.id = this.userNewRoles.newRoleIds[i];
        user.myRoles.push(role);
      }

      apiUserNewRole(user).then(response => {
        rowData.myRoles = [];
        Object.assign(rowData, response.data);
        this.dialogUserRoles = false;
        this.messageSuccess();
      });
      this.isLoading = false;
    },

    enableBtnUserDiabled(rowData) {
      if (this.isNotEmpty(rowData.newIsEnabled)) {
        if (rowData.newIsEnabled === '1') {
          return true;
        } else {
          return false;
        }
      }

      if (rowData.izEnabled === '1') {
        return true;
      } else {
        return false;
      }
    },

    handleResetForm() {
      this.dialogNewUserVisible = true;
      this.beforeCommit = true;
      this.handleResetForm('createUserForm');
      //this.$refs.createUserForm.$emit('el.form.change');
    },

    handleConfirmOK() {
      this.dialogNewUserVisible = false;
    },

    handleDepartmentCancel() {
      this.departmentDrawer.show = false;
    },

    handleDepartmentOk() {
      this.isLoading = true;
      if (this.departmentDrawer.action === 'create') {
        this.newUserForm.newDepartmentId = this.departmentDrawer.id;
        this.newUserForm.newDepartmentName = this.departmentDrawer.name;
        this.$refs.createUserForm.$emit('el.form.change');
      } else if (this.departmentDrawer.action === 'update') {
        let infoMsg = "是否将当前用户:" + this.currentUser.name + " 归属部门设置为 " + this.departmentDrawer.name;
        this.$confirm(infoMsg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.currentUser.newDepartmentId = this.departmentDrawer.id;
          this.currentUser.newDepartmentName = this.departmentDrawer.name;
          apiUserNewDepartment(this.currentUser).then(response => {
            Object.assign(this.currentUser, response.data);
            this.messageSuccess();
          });
        });

      }
      this.departmentDrawer.show = false;
      this.isLoading = false;
    },

    handleUserAudit(rowData) {
      this.isLoading = true;
      let infoMsg = "是否当前用户:" + rowData.name + "调整为新的设置？";
      this.$confirm(infoMsg, '审核调整', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiUserAudit(rowData).then(response => {
          rowData.myRoles = [];
          rowData.newDepartmentName = null;
          rowData.newDepartmentId = null;
          rowData.newIsEnabled = null;
          Object.assign(rowData, response.data);
          this.messageSuccess();
        });
      });
      this.isLoading = false;
    },

    handleUserDisabled(rowData) {
      this.isLoading = true;
      let infoMsg = "是否将当前用户:" + rowData.name + " 设置为离职状态？ 离职后需审核后才能生效！";
      this.$confirm(infoMsg, '设置离职', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiUserDisable(rowData).then(response => {
          Object.assign(rowData, response.data);
          this.messageSuccess();
        });
      });
      this.isLoading = false;
    },

    handlePasswordReset(rowData) {
      this.isLoading = true;
      let infoMsg = "是否将当前用户:" + rowData.name + " 密码重置？";
      this.$confirm(infoMsg, '密码重置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiUserPasswordReset(rowData).then(response => {
          Object.assign(rowData, response.data);
          this.messageSuccess();
        });
      });
      this.isLoading = false;
    },

    handleUserEnabled(rowData) {
      this.isLoading = true;
      let infoMsg = "是否将当前用户:" + rowData.name + " 设置为在职状态？ 用户需再次审核才能正常使用本系统！";
      this.$confirm(infoMsg, '设置在职', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiUserEnable(rowData).then(response => {
          Object.assign(rowData, response.data);
          this.messageSuccess();
        });
      });
      this.isLoading = false;
    },

    departmentTreeCurrentChange(data, node) {
      this.departmentDrawer.name = data.name;
      this.departmentDrawer.id = data.id;
    },

    handleNewDepartment(data) {
      this.currentUser = data;
      this.showDepartmentDrawer('update');
    },

    //update,create,selectUser
    showDepartmentDrawer(action) {
      if (this.departments === undefined) {
        this.callUserListDepartment();
      }

      this.departmentDrawer.show = true;
      this.departmentDrawer.action = action;
    },

    setDownloadIcon() {
      this.isDownloadAllData = !this.isDownloadAllData;
      if (this.isDownloadAllData) {
        this.downloadIcon = "el-icon-s-fold";
      } else {
        this.downloadIcon = "el-icon-circle-check";
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleDownload() {
      if (!this.isDownloadAllData) {
        return this.handleDownloadSelect();
      } else {
        this.isLoading = true;
        this.listQuery.pageSize = this.paginationOption.pageSize;
        //when pageStart is less than 0, fetch all data!
        this.listQuery.pageStart = -1;
        apiUserList(this.listQuery).then(response => {
          this.isLoading = false;
          const data = response.data;
          if (data) {
            const list = data.resultSet;
            import("@/vendor/Export2Excel").then(excel => {
              const data = this.formatJson(this.filterVal, list);
              excel.export_json_to_excel({
                header: this.tHeader,
                data,
                filename: "excel_file_name"
              });
              this.isLoading = false;
            });
          }
        });
        this.isLoading = false;
      }
    },

    handleDownloadSelect() {
      if (this.multipleSelection.length) {
        this.isLoading = true;
        import("@/vendor/Export2Excel").then(excel => {
          const list = this.multipleSelection;
          const data = this.formatJson(this.filterVal, list);
          excel.export_json_to_excel({
            header: this.tHeader,
            data,
            filename: "users_download"
          });
          this.$refs.multipleTable.clearSelection();
          this.isLoading = false;
        });
      } else {
        this.$message({
          message: "请选择您要下载的数据！",
          type: "warning"
        });
      }
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          switch (j) {
            case "izEnabled":
              return this.getDictLabel("user_is_enabled", v[j]);
              break;
            case "userState":
              return this.getDictLabel("user_state", v[j]);
              break;
            case "auditState":
              return this.getDictLabel("audit_state", v[j]);
              break;
            case "roles":
              let rolesInUse = this.getRolesAvailable(v);
              let rolesInCan = this.getRolesUnavailable(v);

              let ret = "";
              for (let i = 0; i < rolesInUse.length; i++) {
                if (i === 0) {
                  ret = rolesInUse[i];
                } else {
                  ret = ret + "," + rolesInUse[i];
                }
              }

              for (let i = 0; i < rolesInCan.length; i++) {
                if (i === 0) {
                  ret = ret + "(" + rolesInCan[i];
                } else {
                  ret = ret + "," + rolesInCan[i];
                }
              }

              if (rolesInCan.length > 0) {
                ret = ret + ")";
              }

              return ret;
              break;
            default:
              return v[j];
          }
        })
      );
    },

    handleSizeChange(val) {
      this.paginationOption.pageSize = val;
    },

    handleCurrentChange(val) {
      this.paginationOption.currentPage = val;
      this.handleGetUserList(val);
    },

    handleResetForm(formName) {
      this.$refs[formName].resetFields();
    },

    handleSumitCreateUser() {
      this.$refs["createUserForm"].validate(valid => {
        if (valid) {
          this.isLoading = true;
          apiUserCreate(this.newUserForm).then(response => {
            this.beforeCommit = false;
            const data = response.data;
            this.newUserForm = data;
            this.$message({
              type: "success",
              message: "用户创建成功，请通知该用户及时完善个人信息！",
              duration: 3000
            });
            //this.dialogNewUserVisible = false;
          });
          this.isLoading = false;
        }
      });
    },

    callUserListDepartment() {
      this.isLoading = true;
      apiUserListDepartment().then(response => {
        this.isLoading = false;
        const data = response.data;
        this.departments = data;
      });
      this.isLoading = false;
    },

    callRoleList() {
      this.isLoading = true;
      apiUserListRole().then(response => {
        this.isLoading = false;
        const data = response.data;
        data.forEach(element => {
          let newItem = Object.assign({}, this.optionItem);
          newItem.value = element.id;
          newItem.label = element.title;
          this.roleOptions.push(newItem);
        });
      });
      this.isLoading = false;
    },

    getOptions(dictKey) {
      return getEntries(dictKey);
    },

    getDictLabel(dictKey, dictValue) {
      return getLabel(dictKey, dictValue);
    },

    getRolesAvailable(row) {
      let ret = [];
      if (row.myRoles !== null && row.myRoles.length > 0) {
        row.myRoles.forEach(element => {
          if (element.relationState === "1") {
            ret.push(element.title);
          }
        });
      }
      return ret;
    },

    getRolesUnavailable(row) {
      let ret = [];
      if (row.myRoles !== null && row.myRoles.length > 0) {
        row.myRoles.forEach(element => {
          if (element.relationState === "0") {
            ret.push(element.title);
          }
        });
      }
      return ret;
    },

    isNotEmpty(v) {
      return v !== undefined && v !== null && v != '';
    },


    handleGetUserList(currentPage) {
      this.isLoading = true;
      if (currentPage === 1) {
        this.paginationOption.currentPage = currentPage;
      }
      this.listQuery.pageSize = this.paginationOption.pageSize;
      this.listQuery.pageStart =
        (this.paginationOption.currentPage - 1) *
        this.listQuery.pageSize;
      apiUserList(this.listQuery).then(response => {
        this.isLoading = false;
        const data = response.data;
        if (data) {
          this.dataList = data.resultSet;
          if (data.total !== -1)
            this.paginationOption.total = data.total;
        }
      });
      this.isLoading = false;
    }
  }
};
</script>
<style scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.my-contain-card {
  padding: 2px;
  width: 100%;
  height: 100%;
}
</style>
